<?php

namespace common\logics;

use common\models\dynamic\DynamicVideo;
use Yii;
use common\helpers\Url;
use yii\helpers\ArrayHelper;
use common\models\dynamic\DynamicLikeLog;
use common\models\dynamic\DynamicStats;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class DynamicLogic extends \common\models\dynamic\Dynamic {

    public function getPublishTime() {
        if ($this->created_at) {
            return Yii::$app->formatter->asRelativeTime($this->created_at);
        }
        return '很久以前';
    }

    public function getPics() {
        $gallery = $this->gallery;
        if (!empty($gallery)) {
            return ArrayHelper::getColumn($gallery, 'picture');
        }
        return [];
    }

    public function getTools() {
        $stats = [
            'likes' => 0,
            'retweets' => 0,
            'comments' => 0,
        ];
        if ($this->stats) {
            $stats['likes'] = $this->stats->likes;
            $stats['retweets'] = $this->stats->retweets;
            $stats['comments'] = $this->stats->comments;
        }
        return $stats;
    }

    public function getLiked() {
        return $this->hasOne(DynamicLikeLog::className(), ['dynamic_id' => 'id'])->andWhere([
            'comment_id' => 0,
            'user_id' => Yii::$app->user->id,
        ])->exists();
    }

    public function getStats() {
        return $this->hasOne(DynamicStats::className(), ['dynamic_id' => 'id'])->andWhere([
            'comment_id' => 0,
        ]);
    }

    public function getCollected() {
        return false;
    }

    public function getRedirect() {
        if ($this->article_id) {
            return Url::h5(['/tsline/article/view', 'id' => $this->article_id]);
        }
        return Url::h5(['/dynamic/view', 'id' => $this->id]);
    }

    public function fields() {
        return [
            'id',
            'format',
            'text' => 'content',
            'pics',
            'video',
            'article',
            'time' => 'publishTime',
            'tools',
            'liked',
            'collected',
            'user',
            'redirect',
            'retweet',
        ];
    }

}
